import { fetchHome } from '../../services/home/home';
import { api } from '../../config/api';
import { request } from '../../utils/request';

Page({
	data: {
		imgSrcs: [],
		swipers: [],
		tabList: [],
		goodsList: [],
		goodsListLoadStatus: 0,
		pageLoading: false,
		current: 1,
		autoplay: true,
		duration: '500',
		interval: 5000,
		navigation: { type: 'dots' },
		swiperImageProps: { mode: 'scaleToFill' },
		tabIndex: 0,
		goodListPagination: {
			index: 0,
			num: 20,
		},
	},
	onShow() {
		this.getTabBar().init();
	},
	onLoad() {
		this.init();
	},
	onReachBottom() {
		if (this.data.goodsListLoadStatus === 0) {
			this.loadGoodsList();
		}
	},
	onPullDownRefresh() {
		this.init();
	},
	init() {
		this.loadHomePage();
	},
	loadHomePage() {
		wx.stopPullDownRefresh();
		this.setData({
			pageLoading: true,
		});
		fetchHome().then(({ swiper, tabList }) => {
			this.setData({
				tabList,
				imgSrcs: swiper.map(x => { return x.image }),
				swipers: swiper,
				pageLoading: false,
			});
			this.loadGoodsList(true);
		});
	},
	tabChangeHandle(e) {
		this.setData({ tabIndex: e.detail.value });
		this.loadGoodsList(true);
	},
	onReTry() {
		this.loadGoodsList();
	},
	async loadGoodsList(fresh = false) {
		if (fresh) {
			wx.pageScrollTo({
				scrollTop: 0,
			});
		}
		this.setData({ goodsListLoadStatus: 1 });
		const pageSize = this.data.goodListPagination.num;
		let pageIndex = fresh ? 0 : this.data.goodListPagination.index + 1;
		try {
			const nextList = await request.get(api.productQuery, {
				page: pageIndex,
				pageSize,
				categoryId: this.data.tabList[this.data.tabIndex].value
			});
			this.setData({
				goodsListLoadStatus: 0,
				goodsList: fresh ? nextList : this.data.goodsList.concat(nextList),
				goodListPagination: { index: pageIndex, num: pageSize }
			});
		} catch (err) {
			this.setData({ goodsListLoadStatus: 3 });
			console.log('home goods load failed', err);
		}
	},

	goodListClickHandle(e) {
		const { index } = e.detail;
		const { spuId } = this.data.goodsList[index];
		wx.navigateTo({
			url: `/pages/goods/details/index?spuId=${spuId}`,
		});
	},

	navToSearchPage() {
		wx.navigateTo({ url: '/pages/goods/search/index' });
	},

	navToActivityDetail({ detail }) {
		const { index } = detail || {};
		const promotionID = this.data.swipers[index].id;
		wx.navigateTo({
			url: `/pages/promotion-detail/index?promotion_id=${promotionID}`,
		});
	},
	gotoLogin() {
		wx.navigateTo({
			url: `/pages/login/index`,
		});
	}
});
